<?php
/**
 * 新闻类型管理
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Types extends CI_Controller
{
    private $token_user,$admin_id;
    public function __construct()
    {
        parent::__construct();
        $this->token_user = check_token();
        $this->admin_id = $this->token_user[0];
        $this->load->model(array('admin_model','admin_group_model', 'news_model', 'news_types_model'));
    }

    public function index()
    {
        //权限检查
        if(!$this->admin_group_model->check_perm('news_type',$this->token_user[3]))
        {
            response_json([],101,'权限错误，请联系管理员');
        }
        $opt = $this->input->get_post('opt');
        // 推荐，置顶，精华状态修改
        if($opt == 'is_show')
        {
            $id   = (integer)$this->input->get_post('id');
            $update     = array(
                $opt => intval($this->input->get_post('val')),
            );
            $this->news_types_model->update($id, $update);
            response_json();
        }
        if($opt == 'add')
        {
            if($_SERVER['REQUEST_METHOD']=='POST')
            {
                $name = $this->input->get_post('name');
                $parent_id = (int)$this->input->get_post('parent_id');
                $sortrank = $this->input->get_post('sortrank');
                $level_num = $this->input->get_post('level_num');
                if(empty($name))
                {
                    response_json([],'101',"请填写分类名称!");
                }
                // 验证分类是否存在
//                $info = $this->news_types_model->get_by_field('name',$name);
//                if(!empty($info))
//                {
//                    response_json([],'101',"该分类已存在!");
//                }

                $insert = array(
                    'name' => $name,
                    'parent_id' => $parent_id,
                    'sortrank' => $sortrank,
                    'level_num' => $level_num,
                    'created_at' => date('Y-m-d H:i:s'),
                );

                $this->news_types_model->insert($insert);
                response_json();
            }
        }

        if($opt == 'edit')
        {
            $id   = (integer)$this->input->get_post('id');
            $info = $this->news_types_model->get_by_id($id);
            if(empty($info))
            {
                response_json([],'101',"参数错误!");
            }
            if($_SERVER['REQUEST_METHOD']=='POST')
            {
                $name = $this->input->get_post('name');
                $parent_id = (int)$this->input->get_post('parent_id');
                $sortrank = $this->input->get_post('sortrank');
                $level_num = $this->input->get_post('level_num');
                if($id <= 0)
                {
                    response_json([],'101',"参数错误!");
                }
                if(empty($name))
                {
                    response_json([],'101',"请填写分类名称!");
                }
                // 验证分类是否存在
//                $info = $this->news_types_model->get_by_field('name',$name);
//                if(!empty($info))
//                {
//                    response_json([],'101',"该分类已存在!");
//                }

                $update = array(
                    'name' => $name,
                    'parent_id' => $parent_id,
                    'sortrank' => $sortrank,
                    'level_num' => $level_num,
                );
                $this->news_types_model->update($id, $update);
                response_json();
            }
        }

        if($opt == 'del')
        {
            $id   = (integer)$this->input->get_post('id');
            $info = $this->news_types_model->get_by_id($id);
            if(empty($info))
            {
                response_json([],'101',"参数错误!");
            }
            // 查找版块下是否存在子分类。
            $child_forums = $this->news_types_model->get_by_field('parent_id',$id);
            if(!empty($child_forums)){
                response_json([],'101',"存在子分类，无法删除!");
            }
            // 是否存在主题
            $threads = $this->news_model->get_by_where('news_type_id='.$id);
            if(!empty($threads)){
                response_json([],'101',"该分类存在文章，无法删除!");
            }
            $this->news_types_model->delete($id);
            response_json();
        }

        $limit     = intval($this->input->get('limit')) > 0 ? $this->input->get('limit') : 20;
        $cur_page      = intval($this->input->get('page'));
        $cur_page   = $cur_page > 0 ? $cur_page : 1;
        $offset     = ($cur_page - 1) * $limit;

        $q			= (string)$this->input->get('q');
        $parent_id			= (int)$this->input->get('pid');

        $where  = "where parent_id=".$parent_id;

        if(!empty($q))
        {
            $where  .= " and `name` like '%".$q."%'";
        }

        $order_by   = "order by `sortrank` desc";
        $result     = $this->news_types_model->result_data($where, $order_by, $offset, $limit);
        // 处理上级版块名称
        if(!empty($result)){
            foreach($result as $key=>$val){
                if($val['parent_id'] == 0){
                    $parent_name = '顶级分类';
                }else{
                    $parent = $this->news_types_model->get_by_id($val['parent_id']);
                    $parent_name = $parent['name'];
                }
                $result[$key]['parent_name'] = $parent_name;
            }
        }
        $total      = $this->news_types_model->result_count($where);
        if($total > 0){
            $_data['code'] = 0;
            $_data['msg'] = 'ok';
        }else{
            $_data['code'] = 101;
            $_data['msg'] = '无数据';
        }
        $_data['data'] = $result;
        $_data['count'] = $total;

        echo json_encode($_data);
    }
    public function cates(){
        // 查询所有版块
        $forums = $this->news_types_model->result_all();
        $res = array();
        $this->math_forum($forums,0,0,[],$res);
        response_json($res);
    }
    public function info(){
        $id   = (integer)$this->input->get_post('id');
        $info = $this->news_types_model->get_by_id($id);
        if(empty($info))
        {
            response_json([],101,'数据不存在');
        }
        response_json($info);
    }

    /**
     * 归类列取版块分类
     * @param $curr_category
     * @param $id
     * @param $level
     * @param array $list
     * @param $res
     * @return array
     */
    private function math_forum($curr_category,$id,$level,$list=[],&$res){
        $list =array();
        foreach ($curr_category as $k=>$v){
            if ($v['parent_id'] == $id){
                for($i=0;$i<$level;$i++){
                    $v['name'] = "--".$v['name'];
                }
                $res[] = $v;
                $math_res = $this->math_forum($curr_category,$v['id'],$level+1,[],$res);
                $v['son'] = $math_res;
                $list[] = $v;
            }
        }
        return $list;
    }
}